package com.ywger.integration.server.impl;

import com.alibaba.fastjson.TypeReference;
import com.ywger.integration.config.IntegrationProperties;
import com.ywger.integration.constants.IntegrationResultCode;
import com.ywger.integration.entity.res.GasPriceRes;
import com.ywger.integration.exception.IntegrationException;
import com.ywger.integration.resttemplate.RestTemplateHelper;
import com.ywger.integration.server.EthIntegration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author chenmeng
 * @date 2021-11-21 17:10
 * @desc
 */
@Service
public class EthIntegrationImpl implements EthIntegration {
    @Autowired
    private RestTemplateHelper restTemplateHelper;

    @Autowired
    private IntegrationProperties properties;

    @Override
    public GasPriceRes getGasPrice(){
        String url = properties.getGasPriceUrl();
        GasPriceRes gasPriceRes = commonGetDeal(url,new TypeReference<GasPriceRes>(){});
        return gasPriceRes;
    }




    public <T> T commonDeal(String url, Object object , TypeReference<T> typeReference) {
        T result = null;
        try {
            result = restTemplateHelper.post(url, object, typeReference);
        } catch (Exception e) {
            //网络异常 未正常返回
            //有返回 状态码非200 返回
            throw IntegrationException.of(IntegrationResultCode.INTEGRATION_ERROR, e);
        }
        return result;

    }

    public <T> T commonGetDeal(String url, TypeReference<T> typeReference, Object ... objects) {
        T result = null;
        try {
            result = restTemplateHelper.get(url, typeReference, objects);
        } catch (Exception e) {
            //网络异常 未正常返回
            //有返回 状态码非200 返回
            throw IntegrationException.of(IntegrationResultCode.INTEGRATION_ERROR, e);
        }
        return result;
    }
}
